<template>
  <div class="run-history-guage">
    <Portal to="right-disable"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <div class="cardHeader">
        <span class="cardTitle">
          <template v-if="inPageName === 'runhistory'">
            All run history in this table
          </template>
          <template v-else>
            Recent run history
          </template>
        </span>
        <template v-if="inPageName === 'runhistory'">
          <el-dropdown @command="changeStatusValue"
                       trigger="click">
            <span class="select-status">
              {{ `Showing ${selectedStatus}` }}
            </span>
            <el-dropdown-menu slot="dropdown"
                              class="bot-run-history-status-dropdown">
              <el-dropdown-item v-for="(item,index) in statusList"
                                :key="index"
                                :command="item.value"
                                :disabled="item.value === selectedStatusValue">
                {{ item.name }}
                <i v-if="item.value === selectedStatusValue"
                   class="cuifont icon_checkmark"></i>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
        <template v-else>
          <div class="select-status"
               @click="detailAllRuns">All runs
          </div>
        </template>
      </div>
      <div class="control-section">
        <div class="content-wrapper">
          <el-table :data="dataList"
                    class="data-table-css">
            <el-table-column prop="createTime"
                             label="Start"
                             align="left">
              <template slot-scope="scope">
                {{ scope.row.createTime | ClientFormatTimer }}
              </template>
            </el-table-column>
            <el-table-column prop="timeSpent"
                             label="Duration (s)"
                             >
            </el-table-column>
            <el-table-column prop="status"
               label="Status"
               align="center">
                            <template slot-scope="scope">
                              <el-tag v-if="scope.row.status === 0"
                                      size="mini"
                                      type="danger">Failed
                              </el-tag>
                              <el-tag v-else-if="scope.row.status === 2"
                                      size="mini"
                                      type="warning">Running
                              </el-tag>
                              <el-tag v-else-if="scope.row.status === 1"
                                      size="mini"
                                      type="success">Succeeded
                              </el-tag>
                              <el-tag v-else
                                      size="mini"
                                      type="info">Unknow
                              </el-tag>
                            </template>
                          </el-table-column>
<!--            <el-table-column prop="status"-->
<!--                             width="180px"-->
<!--                             label="Block Status">-->
<!--              <template slot-scope="scope">-->
<!--                <el-steps>-->
<!--                  <el-step v-for="(item,index) in scope.row.runningList" :key="index" :class="{'success': item.status === 1, 'error': item.status === 0, 'wait': item.status === 2}">-->
<!--                    <div slot="title"></div>-->
<!--                    <el-tooltip class="item" effect="dark" :content="item.scriptName" placement="top" slot="icon">-->
<!--                      <div>-->
<!--                        <i v-if="item.status === 1" class="el-icon-check"></i>-->
<!--                        <i v-if="item.status === 0" class="el-icon-close"></i>-->
<!--                        <i v-if="item.status === 2" class="el-icon-minus"></i>-->
<!--                      </div>-->
<!--                    </el-tooltip>-->
<!--                  </el-step>-->
<!--                </el-steps>-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column-->
<!--                label="Operations"-->
<!--                width="100">-->
<!--              <template slot-scope="scope">-->
<!--                <el-button type="text" size="small" @click="timeLineLog(scope)">Detail</el-button>-->
<!--              </template>-->
<!--            </el-table-column>-->
          </el-table>
          <template v-if="inPageName === 'runhistory'">
            <el-pagination class="list-page"
                           layout="prev, pager, next"
                           background
                           hide-on-single-page
                           :total="dataListPageInfo.total"
                           :page-size="dataListPageInfo.size"
                           :page-count='5'
                           :current-page='dataListPageInfo.current'
                           @current-change="handleCurrentChange">
            </el-pagination>
          </template>
        </div>
      </div>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           @saveGadgetSetting='saveGadgetSetting'/>
    <el-dialog
        @close='close'
        :append-to-body="true"
        :visible.sync="showTimeLine">
      <el-timeline v-loading="timeLineLoading">
        <li class="el-timeline-item" v-for="(item,index) in timeLineData" :key="index">
          <div class="el-timeline-item__tail"></div>
          <div class="el-timeline-item__node el-timeline-item__node--normal" :class="getClass(item.status)"><!----></div><!---->
          <div class="el-timeline-item__wrapper">
            <div class="el-timeline-item__timestamp is-top">{{ item.createTime | ClientFormatTimer }} {{ item.scriptName }}
              <el-tooltip class="item" effect="dark" :content="item.scriptDescription" placement="top">
                <i class="el-icon-info" />
              </el-tooltip>
            </div>
            <div class="el-timeline-item__content">
              <el-card>
                <el-collapse>
                  <el-collapse-item title="INPUT">{{item.inputs}}</el-collapse-item>
                  <el-collapse-item title="OUTPUTS">{{item.outputs}}</el-collapse-item>
                  <el-collapse-item title="ERROR DETAIL">{{item.errorMessage}}</el-collapse-item>
                  <el-collapse-item title="HOW TO FIX">{{item.solution}}</el-collapse-item>
                </el-collapse>
              </el-card>
            </div><!---->
          </div>
        </li>
      </el-timeline>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="showTimeLine = false">{{ $t('confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import { defaultGadgetSettingList } from '@/utils/data-json'
import moment from 'moment'
import store from '@/store'

export default {
  mixins: [mixinGadgetViewModule],
  components: { model: () => import('@/components/gadget/query-model/query-model') },
  data () {
    return {
      gadgetSetting: {},
      mixinViewModuleOptions: {
        pageId: this.pageId
      },
      isGridInit: false,
      dataList: [],
      dataListPageInfo: {
        total: 0,
        current: 1,
        size: 10
      },
      loading: false,
      heightoffset: 60,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'customizedbotdetailrunhistorygadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'customizedbotdetailrunhistorygadget' }).gadgetSetting
        }
      },
      queryId: '',
      widgetName: '',
      botDetailSlicer: {},
      botDetailInfo: {},
      originBotInfo: null,
      isEditMode: false,
      statusList: [
        {
          name: 'All runs',
          value: 999
        },
        {
          name: 'Successful runs',
          value: 1
        },
        {
          name: 'Failed runs',
          value: 0
        },
        {
          name: 'Running',
          value: 2
        }
      ],
      selectedStatusValue: 999,
      showTimeLine: false,
      timeLineLoading: true,
      timeLineData: []
    }
  },
  beforeCreate () {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created () {
    this.getQureAll()
    // this.query()
    this.subscribeMessage('runReport', this.getQureAll)
    this.$store.state.isWidget = false
  },
  computed: {
    selectedStatus () {
      if (this.statusList.find(e => e.value === this.selectedStatusValue)) {
        let temp = this.statusList.find(e => e.value === this.selectedStatusValue).name
        temp = temp.replace(temp[0], temp[0].toLowerCase())
        return temp
      } else {
        return 'all Runs'
      }
    },
    inPageName () {
      if (this.gadgetInfo.w === 12) {
        return 'runhistory'
      } else {
        return 'detail'
      }
    }
  },
  watch: {
    isEditMode (val) {
      if (val) {
        this.originBotInfo = this._.cloneDeep(this.botDetailInfo)
      } else {
        this.originBotInfo = null
      }
    }
  },
  filters: {
    timeFormat: val => {
      if (val >= 0) {
        if (val > 86400) {
          return `More than ${parseInt(val / 86400)} days`
        } else {
          let s = val % 60
          let m = parseInt(val / 60 % 60)
          let h = parseInt(val / 3600)
          return `${h < 10 ? '0' + h : h}:${m < 10 ? '0' + m : m}:${s < 10 ? '0' + s : s}`
        }
      } else {
        return '00:00:00'
      }
    },
    startTimeFormat: val => {
      if (moment(val).isValid()) {
        return `${moment.tz(val, store.state.user.timezoneId).format('MMM DD HH:mm A')} (${moment.tz(val, store.state.user.timezoneId).fromNow()})`
      } else {
        return val
      }
    }
  },
  mounted () {

  },
  methods: {
    saveGadgetSetting () {
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.getQureAll()
    },
    queryModelPreview () {
      this.getQureAll()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = newH * 20 - this.heightoffset - 15
      this.gadgetWidth = newWPx
    },
    handleCurrentChange (current) {
      this.dataListPageInfo.current = current
      this.getQureAll()
    },
    query () {
      if (!this.botDetailSlicer.botId) {
        return false
      }
      this.dataList = []
      this.loading = true
      let params = {
        botId: this.botDetailSlicer.botId,
        current: this.dataListPageInfo.current,
        size: this.dataListPageInfo.size,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName
      }
      if (this.selectedStatusValue !== 999) {
        params['status'] = this.selectedStatusValue
      }
      this.$interface.bots.getBotRunHistoryList(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataList = res.data.records
        this.dataListPageInfo.total = res.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    getQureAll () {
      try {
        let hasQure = window.location.search.split('?').length > 1
        hasQure && window.location.search.split('?')[1].split('&').map(e => {
          this.$set(this.botDetailSlicer, e.split('=')[0], e.split('=')[1])
        })
        if (this.botDetailSlicer.originalId) {
          this.getBotIdByOriginalId(this.botDetailSlicer.originalId)
        } else {
          this.query()
        }
      } catch (error) {
      }
    },
    changeStatusValue (val) {
      this.selectedStatusValue = val
      this.$nextTick(() => {
        this.query()
      })
    },
    detailAllRuns () {
      this.publishMessage('detailAllRuns')
    },
    getBotIdByOriginalId (originalId) {
      this.$interface.bots.getBotIdByOriginalId(originalId).then(({ data: res }) => {
        this.$set(this.botDetailSlicer, 'botId', res.data)
        this.query()
      }).catch(() => {
      })
    },
    timeLineLog (scope) {
      this.showTimeLine = true
      this.timeLineLoading = true
      this.$interface.bots.getBotHistoryDetail({
        serialId: scope.row.serialId,
        botId: this.botDetailSlicer.botId
      }).then(res => {
        this.timeLineData = res.data.data
        this.timeLineLoading = false
      })
    },
    getClass (status) {
      let color = null
      switch (String(status)) {
        case '1': // success
          color = 'el-timeline-item__node--success'
          break
        case '0': // fail
          color = 'el-timeline-item__node--danger'
          break
        case '2': // running
          color = 'el-timeline-item__node--'
          break
        default:
          color = 'el-timeline-item__node--'
      }
      return color
    },
    close () {
      this.timeLineData = []
    }
  }
}
</script>
<style scoped lang='scss'>
.el-collapse{
  border: none;
}
.el-collapse-item__wrap{
  border: none;
}
.el-steps{
  height: 24px;
}
.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 0;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardTitle {
  font-size: 16px;
  color: #404040;
  font-weight: 700;
  line-height: 24px;
}

.data-table-css {
  border-left: 1px solid #f0f0f0;
  border-right: 1px solid #f0f0f0;
}

.select-status {
  cursor: pointer;
  color: $--theme-color;
}
</style>
<style lang="scss">
.run-history-guage {
  .el-table__header thead th {
    background-color: #f8f8f8;
    padding: 9px 0;
  }
  .el-table__body tbody td {
    padding: 4px 0;
  }

  .list-page {
    margin-top: 0;
    padding: 9px;
    border-left: 1px solid #f0f0f0;
    border-right: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
    background-color: #f8f8f8;
    text-align: right;

    & > button {
      background-color: #fff !important;
    }
  }

  .el-pagination.is-background .el-pager li:not(.disabled) {
    background-color: #fff;
  }

  .el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: $--theme-color;
    color: #fff;
  }

  .el-tag--mini {
    width: 90px;
  }
  .success .el-step__head{
    color: #67c23a;
    border-color: #67c23a;
  }
  .error .el-step__head{
    color: #f78989;
    border-color: #f78989;
  }
  .wait .el-step__head{
    color: #c0c4cc;
    border-color: #c0c4cc;
  }
}

.bot-run-history-status-dropdown {
  .el-dropdown-menu__item {
    padding-right: 40px;
  }

  .el-dropdown-menu__item.is-disabled {
    background-color: $--theme-color-background;
    color: $--theme-color;

    .icon_checkmark {
      position: absolute;
      right: 0;
      width: 24px;
      height: 100%;
    }
  }
}
</style>
